/* eslint-disable */
import { postForm } from '@/utils/request';
import domain from '@/utils/domain';
import { setToken } from '@/utils/tokenStore';

const tokenUrl = `${domain.user}/oauth2/token`;
const clientId = 'management-Client';

/**
 * 获取Token
 * @returns {Promise.<void>}
 */
export async function getToken({ username, password }) {
  const param = {
    grant_type: 'password',
    client_id: clientId,
    username,
    password,
  };
  return postForm(tokenUrl, param)
    .then(response => response.json())
    .then(json => {
      if (json.code === 0) {
        setToken(json.data.access_token, json.data.refresh_token);
      }
      return json;
    });
}

/**
 * 刷新Token
 * @returns {Promise.<void>}
 */
export async function refreshToken(refreshToken) {
  const param = {
    grant_type: 'refresh_token',
    client_id: clientId,
    refresh_token: refreshToken,
  };
  return postForm(tokenUrl, param)
    .then(response => response.json())
    .then(json => {
      if (json.code === 0) {
        setToken(json.data.access_token, json.data.refresh_token);
      }
      return json;
    });
}
